package com.sasis.webapp.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sasis.model.BasePermission;
import com.sasis.model.BasePrincipal;
import com.sasis.model.BaseSubject;
import com.sasis.model.CurrentUser;
import com.sasis.model.Permission;
import com.sasis.model.User;
import com.sasis.service.PermissionService;

public class AllowTag extends TagSupport {
	
	private static final long serialVersionUID = 1L;
	
	private static final Log log = LogFactory.getLog(AllowTag.class);
	
	private Long pid;
	
	public int doStartTag() throws JspException {
		if (isShow()) {
			return EVAL_BODY_INCLUDE;
		} else {
        	return SKIP_BODY;
        }
	}

	public void setPid(String pid) {
		this.pid = new Long(pid);
	}
	
	protected boolean isShow() {
/*		try {
*/			log.debug("----------validate");
			if (pid == null) {
				return false;
			}
			log.debug("----------permissionId:" + pid);
		//	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//	Object obj = authentication.getPrincipal();
			User user = CurrentUser.get();
/*			if (obj instanceof User) {
				User user = (User)obj;
*/				log.debug("----------userId:" + user.getId());
				PermissionService permissionService = (PermissionService) WebApplicationContextUtils.getRequiredWebApplicationContext(pageContext.getServletContext()).getBean("permissionService");
				Permission permission = new BasePermission(new BasePrincipal(user.getId(), false), new BaseSubject(pid, false), true);
				return permissionService.validate(permission);
/*			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
*/	}

}
